package com.jinyang.jetpackdemo.util.event

import java.util.*

/**
 * @Author: LiuJinYang
 * @CreateDate: 2021/11/24
 * @Description:
 */
class LiveDataBus private constructor() {
    private val bus: MutableMap<String, EventMutableLiveData<Any>>

    @Synchronized
    fun <T> with(key: String, type: Class<T>?): EventMutableLiveData<T> {
        if (!bus.containsKey(key)) {
            bus[key] = EventMutableLiveData()
        }
        return bus[key] as EventMutableLiveData<T>
    }

    fun with(key: String): EventMutableLiveData<Any> {
        return with(key, Any::class.java)
    }

    fun <T> with(eventType: Class<T>): EventMutableLiveData<T> {
        return with(eventType.name, eventType)
    }

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { LiveDataBus() }
    }

    init {
        bus = HashMap()
    }
}